package com.live.shop.scene.client;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.FocusMeteringAction;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;
import com.live.shop.R;
import com.live.shop.model.CommentModel;
import com.live.shop.model.IpconfigModel;
import com.live.shop.model.KeywordModel;
import com.live.shop.model.KeywordRecordModel;
import com.live.shop.model.MusicModel;
import com.live.shop.model.ProductGroupModel;
import com.live.shop.model.ProductMaterialRecordModel;
import com.live.shop.model.PrologueModel;
import com.live.shop.model.UserModel;
import com.live.shop.scene.ws.WsClient;
import com.live.shop.scene.ws.WsMessageEvent;
import com.live.shop.scene.ws.WsStatus;
import com.live.shop.sql.CommentsListDatabase;
import com.live.shop.sql.IpconfigDatabase;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.GetUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WsHomeClientActivity extends AppCompatActivity {

    //文件保存路径
    String fileDir = "";
    FileOutputStream fos;

    private PowerManager.WakeLock wakeLock = null;
    //底层view
    ConstraintLayout ws_home_client_constraintLayout;
    //是否已连接
    boolean isConnected = false;
    IpconfigDatabase db;
    AlertDialog dialog;
    //相机进程提供者
    private ProcessCameraProvider processCameraProvider;
    private Camera camera;

    CameraSelector DEFAULT_FRONT_CAMERA =
            new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_FRONT).build();
    CameraSelector DEFAULT_BACK_CAMERA  =
            new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();

    //摄像头预览
    PreviewView previewView;

    CommentsListDatabase comDb;
    //数据
    UserModel userModel;
    List<KeywordModel> keyList = new ArrayList<>();
    List<PrologueModel> proList = new ArrayList<>();
    List<MusicModel> musicList = new ArrayList<>();
    List<ProductGroupModel> groupList = new ArrayList<>();
    List<String> fileNoExistsList = new ArrayList<>();

    boolean prologuesStatus = false;//开场白状态
    int prologuePlayCurrentPosition = -1;//播放位置
    MediaPlayer prologuePlayer;

    boolean musicStatus = false;//音乐状态
    MediaPlayer musicPlayer;

    boolean answerStatus = false;//回复总控状态

    boolean qaKeywordStatus = false;//问答回复状态
    MediaPlayer qaKeywordPlayer;

    boolean materialKeywordStatus = false;//素材回复开关
    MediaPlayer materialKeywordPlayer;

    int materialType;//素材类型 0.图片 1.视频 2.文字

    boolean cameraOpenStatus = true; //摄像头状态 true已打开 false已关闭
    int cameraDirection = 1; //摄像头方向 0前置 1后置(默认)
    boolean videoVolumeStatus = false;//视频音量状态 true已打开 false已关闭
    int productGroupIndex = 0;//当前产品组键值

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /* 在super.onCreate()之前添加代码块 start */
        /* 【全屏显示】隐藏标题栏 */
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        /* 【全屏显示】隐藏状态栏 */
        supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        getWindow().setAttributes(lp);
        /* 在super.onCreate()之前添加代码块 end */

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ws_home_client);
        //EventBus注册
        EventBus.getDefault().register(this);

        comDb = new CommentsListDatabase(getApplicationContext());
        db = new IpconfigDatabase(getApplicationContext());
        dialog = new AlertDialog.Builder(this).create();

        // 获取当前Activity的LayoutInflater对象
        ws_home_client_constraintLayout = findViewById(R.id.ws_home_client_constraintLayout);

        fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+"/zhiboMusic/";
        File folder = new File(fileDir);
        //文件夹不存在 则创建
        if (!folder.exists()) folder.mkdirs();
        //初始化锁
        acquireWakeLock();

        if(!isConnected){
            dialog_connected();
        }
    }
    //=======================背景图片=================================
    //初步加载图片素材
    public void createImage(int materialIndex){
        // 创建一个新的View对象
        try {
            ProductMaterialRecordModel model = groupList.get(productGroupIndex).getListRecord().get(materialIndex);
            if(model.isViewStatus()){
                Log.d(GetUtil.TAG,"当前素材【"+model.getMaterialName()+"】已加载");
                return;
            }

            String file_name = Paths.get(model.getMaterialFilepath()).getFileName().toString();
            File file = new File(fileDir+file_name);
            //文件是否存在
            if(!file.exists()){
                Log.d(GetUtil.TAG,"当前素材【"+model.getMaterialName()+"】文件不存在");
                return;
            }
            // 创建一个新的ImageView
            ImageView imageView = new ImageView(this);
            // 设置图片资源
            Bitmap imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
            imageView.setImageBitmap(imageBitmap);

            //添加到view后才可以设置(必须在动态设置缩放位置之前)
            groupList.get(productGroupIndex).getListRecord().get(materialIndex).setImageView(imageView);
            //图片动态设置缩放
            setImageScale(materialIndex);
            //图片动态设置位置
            setImageLocation(model.getLocationX(),model.getLocationY(),materialIndex);

            //隐藏状态 0 显示 1隐藏
            if(model.getHideState() == 0){
                groupList.get(productGroupIndex).getListRecord().get(materialIndex).setViewStatus(true);
                ws_home_client_constraintLayout.addView(imageView);
            }

            //设置延迟进行移除（自定义时间 或者 跟随回复）
            if(model.getMaterialShowState() != 0){
                //素材展示时间状态[确保隐藏状态为 0显示，否则不生效]  0长时间（将按照设置的展示时间） 1自义定  2跟随关键词回复时间（必须设置关键词）
                if(model.getMaterialShowState() == 1){
                    imageView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            groupList.get(productGroupIndex).getListRecord().get(materialIndex).setViewStatus(false);
                            ws_home_client_constraintLayout.removeView(imageView);
                        }
                    },model.getMaterialKeyShowtime()* 1000L);
                }else{
                    //是否添加了回复
                    if(model.getAnswerState() != 0) {
                        imageView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                groupList.get(productGroupIndex).getListRecord().get(materialIndex).setViewStatus(false);
                                ws_home_client_constraintLayout.removeView(imageView);
                            }
                        },getAudioDuration(model.getAnswerAudio()));
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //图片动态设置位置
    public void setImageLocation(int moveX,int moveY,int materialIndex){
        ProductMaterialRecordModel model = groupList.get(productGroupIndex).getListRecord().get(materialIndex);
        //开始变化
        ImageView imageView = model.getImageView();
        // 计算ImageView的中心点坐标
        float centerX = imageView.getX() + imageView.getWidth() / 2;
        float centerY = imageView.getY() + imageView.getHeight() / 2;
        Log.d(GetUtil.TAG,"moveX:"+moveX+",moveY:"+moveY);
        // 计算新的位置
        float newX = centerX - imageView.getWidth() / 2 + moveX;
        float newY = centerY - imageView.getHeight() / 2 + moveY;
        // 设置新的位置
        imageView.setX(newX);
        imageView.setY(newY);
    }
    //图片动态设置缩放
    public void setImageScale(int materialIndex){
        ProductMaterialRecordModel model = groupList.get(productGroupIndex).getListRecord().get(materialIndex);
        //开始变化
        ImageView imageView = model.getImageView();

        // 根据中心点进行缩放
        float scaleFactor = (float) model.getScaleRate() / (float) 100;
        imageView.setScaleX(scaleFactor);
        imageView.setScaleY(scaleFactor);
    }
    //=======================视频=================================
    public void createVideo(int materialIndex){
        //服务端文件路径
        ProductMaterialRecordModel model = groupList.get(productGroupIndex).getListRecord().get(materialIndex);
        if(model.isViewStatus()){
            Log.d(GetUtil.TAG,"当前素材【"+model.getMaterialName()+"】已加载");
            return;
        }

        String file_name = Paths.get(model.getMaterialFilepath()).getFileName().toString();
        File file = new File(fileDir+file_name);
        //文件是否存在
        if(!file.exists()){
            Log.d(GetUtil.TAG,"当前素材【"+model.getMaterialName()+"】文件不存在");
            return;
        }

        VideoView videoView = new VideoView(this);
        //设置路径
        videoView.setVideoPath(file.getAbsolutePath());
        //设置MediaPlayer实例
        MediaController media = new MediaController(this);
        //设置控制器隐藏
        media.setVisibility(View.GONE);
        videoView.setMediaController(media);
        media.setMediaPlayer(videoView);
        //不可点击和不可启用
        media.setEnabled(false);
        media.setClickable(false);

        //播放状态监听事件
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //播放完成

            }
        });
        //准备状态监听
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //视频音量状态 true已打开 false已关闭
                if(!videoVolumeStatus) mp.setVolume(0f, 0f);

                //设置循环播放
                mp.setLooping(true);
            }
        });
        groupList.get(productGroupIndex).getListRecord().get(materialIndex).setVideoView(videoView);

        //视频动态设置缩放
        setVideoScale(materialIndex);
        //视频动态设置位置
        setVideoLocation(model.getLocationX(),model.getLocationY(),materialIndex);
        //开始播放
        videoView.start();

        //隐藏状态 0 显示 1隐藏
        if(model.getHideState() == 0){
            groupList.get(productGroupIndex).getListRecord().get(materialIndex).setViewStatus(true);
            ws_home_client_constraintLayout.addView(videoView);
        }

        //设置延迟（自定义时间 或者 跟随回复）
        if(model.getMaterialShowState() != 0){
            //素材展示时间状态[确保隐藏状态为 0显示，否则不生效]  0长时间（将按照设置的展示时间） 1自义定  2跟随关键词回复时间（必须设置关键词）
            switch (model.getMaterialShowState()){
                case 0://一直
                    break;
                case 1://自义定
                    videoView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            groupList.get(productGroupIndex).getListRecord().get(materialIndex).setViewStatus(false);
                            ws_home_client_constraintLayout.removeView(videoView);
                            media.hide();
                        }
                    },model.getMaterialKeyShowtime()* 1000L);
                    break;
                case 2://跟随
                    //是否添加了回复
                    if(model.getAnswerState() != 0) {
                        videoView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                groupList.get(productGroupIndex).getListRecord().get(materialIndex).setViewStatus(false);
                                ws_home_client_constraintLayout.removeView(videoView);
                                media.hide();
                            }
                        },getAudioDuration(model.getAnswerAudio()));
                    }
                    break;
            }
        }

    }
    //视频动态设置位置
    public void setVideoLocation(int moveX,int moveY,int materialIndex){
        ProductMaterialRecordModel model = groupList.get(productGroupIndex).getListRecord().get(materialIndex);
        //开始变化
        VideoView videoView = model.getVideoView();
        // 计算ImageView的中心点坐标
        float centerX = videoView.getX() + videoView.getWidth() / 2;
        float centerY = videoView.getY() + videoView.getHeight() / 2;
        // 计算新的位置
        float newX = centerX - videoView.getWidth() / 2 + moveX;
        float newY = centerY - videoView.getHeight() / 2 + moveY;
        // 设置新的位置
        videoView.setX(newX);
        videoView.setY(newY);
    }
    //视频动态设置缩放
    public void setVideoScale(int materialIndex){
        ProductMaterialRecordModel model = groupList.get(productGroupIndex).getListRecord().get(materialIndex);
        //开始变化
        VideoView videoView = model.getVideoView();

        // 根据中心点进行缩放
        float scaleFactor = (float) model.getScaleRate() / (float) 100;
        videoView.setScaleX(scaleFactor);
        videoView.setScaleY(scaleFactor);
    }
    //=======================摄像头=================================
    //打开摄像头
    public void openCamera(){
        // 创建一个新的View对象
        previewView = new PreviewView(this);
        //这里可以设置具体值，摄像头预览不需要设置，这里省略...

        ConstraintLayout.LayoutParams cameraParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        cameraParams.width = ws_home_client_constraintLayout.getWidth();
        cameraParams.height = ws_home_client_constraintLayout.getHeight();

        // 将新创建的TextView添加到LinearLayout中
        ws_home_client_constraintLayout.addView(previewView,0,cameraParams);

        previewView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getPointerCount() == 1){
                    //对焦
                    FocusMeteringAction action = new FocusMeteringAction.Builder(previewView.getMeteringPointFactory().createPoint(event.getX(),event.getY())).build();
                    if(camera != null){
                        //摄像头聚焦
                        camera.getCameraControl().startFocusAndMetering(action);
                    }
                }
                return true;
            }
        });

        //默认打开后置摄像头
        startCameraX(previewView,DEFAULT_BACK_CAMERA);
    }
    //关闭摄像头
    public void closeCamera(){
        //关闭摄像头
        if(camera != null){
            // 取消预览
            processCameraProvider.unbindAll();
            // 释放camera资源
            camera = null;
        }
        //移除组件
        ws_home_client_constraintLayout.removeView(previewView);
    }
    //显示摄像头预览
    private void startCameraX(PreviewView previewView,CameraSelector cameraSelector) {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture =
                ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                //获取当前提供者列表 只允许一个进程使用相机
                processCameraProvider = cameraProviderFuture.get();
                //解绑所有进程
                processCameraProvider.unbindAll();
                //构建相机预览流
                Preview preview = new Preview.Builder().build();
                //绑定生命周期 将决定相机何时打开、启动、停止和关闭
                camera = processCameraProvider.bindToLifecycle((LifecycleOwner)this,cameraSelector, preview);
                //设置预览
                preview.setSurfaceProvider(previewView.getSurfaceProvider());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(this));
    }
    //切换前后摄像头
    public void setLensFacingDirection(){
        //是否打开了摄像头
        if(!cameraOpenStatus) return;
        if(cameraDirection == 1){
            startCameraX(previewView,DEFAULT_BACK_CAMERA);
        }else{
            startCameraX(previewView,DEFAULT_FRONT_CAMERA);
        }
    }

    //视频动态设置位置
    public void setCameraLocation(int moveX,int moveY){
        // 计算ImageView的中心点坐标
        float centerX = previewView.getX() + previewView.getWidth() / 2;
        float centerY = previewView.getY() + previewView.getHeight() / 2;
        // 计算新的位置
        float newX = centerX - previewView.getWidth() / 2 + moveX;
        float newY = centerY - previewView.getHeight() / 2 + moveY;
        // 设置新的位置
        previewView.setX(newX);
        previewView.setY(newY);
    }
    //视频动态设置缩放
    public void setCameraScale(float scaleFactor){
        // 根据中心点进行缩放
        float newScaleFactor = scaleFactor / (float) 100;
        previewView.setScaleX(newScaleFactor);
        previewView.setScaleY(newScaleFactor);
    }

    //=======================摄像头=================================
    //消息处理机制
    private void MessageReceive(String message){
        try {
            JSONObject json = new JSONObject(message);
            String command = json.getString("command");
            switch (command){
                case WsStatus.mateialCheck://接收数据校验【完结】
                    setDataToList(json.getString("param"));
                    //如果数据的文件有不存在的
                    if(fileNoExistsList.size() > 0){
                        //请求开始同步，发送同步信息
                        SendMessage(WsStatus.mateialSync,fileNoExistsList.size());
                    }
                    break;
                case WsStatus.mateialUpdate://切换素材【完结】
                    //素材类型 0.图片 1.视频 2.文字
                    materialType = groupList.get(productGroupIndex).getListRecord().get(json.getInt("param")).getMaterialType();
                    if(materialType == 1) createVideo(json.getInt("param"));
                    else createImage(json.getInt("param"));
                    break;
                case WsStatus.mateialScaleRate://缩放素材
                    JSONObject scaleJson = json.getJSONObject("param");
                    groupList.get(productGroupIndex).getListRecord().get(scaleJson.getInt("materialIndex")).setScaleRate(scaleJson.getInt("progress"));
                    //动态设置缩放
                    if(materialType == 1) setVideoScale(scaleJson.getInt("materialIndex"));
                    else setImageScale(scaleJson.getInt("materialIndex"));
                    break;
                case WsStatus.mateialHideState://素材显隐【完结】
                    JSONObject hideJson = json.getJSONObject("param");
                    groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).setHideState(hideJson.getInt("hidestate"));
                    //隐藏状态 0 显示 1隐藏
                    if(hideJson.getInt("hidestate") == 0){
                        //需要显示
                        if(materialType==1) ws_home_client_constraintLayout.addView(groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).getVideoView());
                        else ws_home_client_constraintLayout.addView(groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).getImageView());

                        groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).setViewStatus(true);
                    }else{
                        //需要隐藏
                        if(materialType==1)  ws_home_client_constraintLayout.removeView(groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).getVideoView());
                        else ws_home_client_constraintLayout.removeView(groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).getImageView());

                        groupList.get(productGroupIndex).getListRecord().get(hideJson.getInt("materialIndex")).setViewStatus(false);
                    }
                    break;
                case WsStatus.mateialShowState://素材展示时间状态【完结】
                    JSONObject showStateJson = json.getJSONObject("param");
                    groupList.get(productGroupIndex).getListRecord().get(showStateJson.getInt("materialIndex")).setMaterialShowState(showStateJson.getInt("showstate"));
                    break;
                case WsStatus.mateialLocation://素材位置
                    JSONObject localJson = json.getJSONObject("param");
                    int local_x = groupList.get(productGroupIndex).getListRecord().get(localJson.getInt("materialIndex")).getLocationX();
                    int local_y = groupList.get(productGroupIndex).getListRecord().get(localJson.getInt("materialIndex")).getLocationY();
                    groupList.get(productGroupIndex).getListRecord().get(localJson.getInt("materialIndex")).setLocationX(localJson.getInt("x")+local_x);
                    groupList.get(productGroupIndex).getListRecord().get(localJson.getInt("materialIndex")).setLocationY(localJson.getInt("y")+local_y);
                    //动态设置位置
                    if(materialType == 1) setVideoLocation(localJson.getInt("x"),localJson.getInt("y"),localJson.getInt("materialIndex"));
                    else setImageLocation(localJson.getInt("x"),localJson.getInt("y"),localJson.getInt("materialIndex"));
                    break;
                case WsStatus.mateialShowTime://自定义时间【完结】
                    JSONObject showTimeJson = json.getJSONObject("param");
                    groupList.get(productGroupIndex).getListRecord().get(showTimeJson.getInt("materialIndex")).setMaterialKeyShowtime(showTimeJson.getInt("showtime"));
                    break;
                case WsStatus.groupUpdate://产品组切换【完结】
                    //移除当前产品组所有view ProductMaterialRecordModel m:groupList.get(productGroupIndex).getListRecord()
                    for (int i = 0 ; i < groupList.get(productGroupIndex).getListRecord().size() ;i++) {
                        ProductMaterialRecordModel m = groupList.get(productGroupIndex).getListRecord().get(i);
                        //隐藏状态 0 显示 1隐藏
                        if(m.getHideState() == 0){
                            //显示的都要设置移除和状态
                            if(m.getMaterialType() == 1)  ws_home_client_constraintLayout.removeView(m.getVideoView());
                            else ws_home_client_constraintLayout.removeView(m.getImageView());
                            groupList.get(productGroupIndex).getListRecord().get(i).setViewStatus(false);
                        }
                    }
                    productGroupIndex = json.getInt("param");

                    break;
                case WsStatus.transFileOver://发送文件完毕【完结】
                    transFileOver(json.getString("param"));
                    break;
                case WsStatus.commentVlaue://评论
                    JSONObject commentJson = json.getJSONObject("param");
                    startTask(commentJson.getString("userName"),commentJson.getString("userCom"),commentJson.getInt("type"));
                    break;
                case WsStatus.cameraUpdown://开关摄像头【完结】
                    cameraOpenStatus = json.getBoolean("param");
                    if(cameraOpenStatus) openCamera();
                    else closeCamera();
                    break;
                case WsStatus.cameraChange://切换摄像头【完结】
                    cameraDirection = json.getInt("param");
                    setLensFacingDirection();
                    break;
                case WsStatus.cameraLocation://调整摄像位置【完结】
                    JSONObject cameraLocalJson = json.getJSONObject("param");
                    setCameraLocation(cameraLocalJson.getInt("x"),cameraLocalJson.getInt("y"));
                    break;
                case WsStatus.cameraScaleRate://调整摄像缩放【完结】
                    setCameraScale(json.getInt("param"));
                    break;
                case WsStatus.answerStatus://回复总控开关【完结】
                    answerStatus = json.getBoolean("param");
                    if(!answerStatus){
                        qaKeywordStatus = false;//问答回复状态
                        if(qaKeywordPlayer != null){
                            qaKeywordPlayer.release();
                            qaKeywordPlayer = null;
                        }
                        materialKeywordStatus = false;//素材回复开关
                        if(materialKeywordPlayer != null){
                            materialKeywordPlayer.release();
                            materialKeywordPlayer = null;
                        }
                    }
                    break;
                case WsStatus.qaKeywordStatus://问答回复开关【完结】
                    qaKeywordStatus = json.getBoolean("param");
                    if(!qaKeywordStatus){
                        if(qaKeywordPlayer != null){
                            qaKeywordPlayer.release();
                            qaKeywordPlayer = null;
                        }
                    }
                    break;
                case WsStatus.materialKeywordStatus://素材回复开关【完结】
                    materialKeywordStatus = json.getBoolean("param");
                    if(!materialKeywordStatus){
                        if(materialKeywordPlayer != null){
                            materialKeywordPlayer.release();
                            materialKeywordPlayer = null;
                        }
                    }
                    break;
                case WsStatus.prologuesStatus://话术开关【完结】
                    prologuesStatus = json.getBoolean("param");
                    if(prologuesStatus){
                        ProloguePlay();
                    }else{
                        if(prologuePlayer != null){
                            prologuePlayer.release();
                            prologuePlayer = null;
                        }
                    }
                    break;
                case WsStatus.musicStatus://音乐开关【完结】
                    musicStatus = json.getBoolean("param");
                    if(musicStatus){
                        MusicPlay();
                    }else{
                        if(musicPlayer != null){
                            musicPlayer.release();
                            musicPlayer = null;
                        }
                    }
                    break;
                case WsStatus.videoVolume://视频静音【完结】
                    videoVolumeStatus = json.getBoolean("param");
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //=======================播放区域=================================
    private void startTask(String userName,String userCom,int type){
        //未开启回复总控
        if(!answerStatus) return;

        //素材回复(优先)
        if(materialKeywordStatus){
            int comid = 0;
            int materialPosition = -1;
            //查找当前产品组的所有素材
            List<ProductMaterialRecordModel> recordList = groupList.get(productGroupIndex).getListRecord();
            for (int a = 0 ; a < recordList.size();a++) {
                //查找关键词不为空的
                if(recordList.get(a).getKeyword() != null && !recordList.get(a).getKeyword().equals("")){
                    String[] kws = recordList.get(a).getKeyword().split("\\|");
                    for (String k:kws) {
                        //是否包含该关键词
                        if(userCom.contains(k)){
                            materialPosition = a;//当前该关键词位置
                            break;
                        }
                    }
                    if(materialPosition != -1) break;
                }
            }
            //是否找到
            if(materialPosition != -1){
                //显示该素材
                ProductMaterialRecordModel thisModel = recordList.get(materialPosition);
                //素材类型 0.图片 1.视频 2.文字
                if(thisModel.getMaterialType() == 1) createVideo(materialPosition);
                else createImage(materialPosition);

                //是否设置了回复音频
                if(thisModel.getAnswerState() != 0){
                    //有回复音频
                    String materialFilePath = fileDir+Paths.get(recordList.get(materialPosition).getAnswerAudio()).getFileName().toString();
                    //是否开启评论记忆回复
                    if(userModel.getKeywordKeeptype() == 1){
                        comid = (int)comDb.insertData2(userName,userCom,type,3,materialFilePath);
                    }
                    //第二步：判断当前是否正在回复
                    if(materialKeywordPlayer != null) return;
                    //没有正在素材回复的，更新评论回复状态
                    comDb.updateKeywordReply(comid,1);
                    //开始播放素材的回复（关闭话术和问答回复）
                    MaterialKeywordPlay(materialFilePath);
                    //不需要往下走了
                    return;
                }
            }
        }

        //再判断是否开启问答回复
        if(!qaKeywordStatus)  return;

        int qaKeywordPosition = -1;
        //第一步：先匹配回复
        for (int a = 0 ; a < keyList.size();a++) {
            String[] kws = keyList.get(a).getKeyword().split("\\|");
            for (String k:kws) {
                //是否包含该关键词
                if(userCom.contains(k)){
                    qaKeywordPosition = a;//当前该关键词位置
                    break;
                }
            }
            if(qaKeywordPosition != -1) break;
        }
        //是否匹配到关键词
        if(qaKeywordPosition != -1){
            //找到该关键词的某个回复音频
            String qaRecordFilePath="";
            List<KeywordRecordModel> recordList = keyList.get(qaKeywordPosition).getListRecord();
            //两种方式都会最终获取到音频路径
            if(userModel.getProloguePlaytype() == 1){
                //随机
                int randomNum = 0;
                //是否为多个
                if(recordList.size() != 1){
                    Random random = new Random();
                    randomNum = random.nextInt(recordList.size());
                }
                qaRecordFilePath = fileDir+Paths.get(recordList.get(randomNum).getAnswerAudio()).getFileName().toString();
            }else{
                int minPlayNum = -1;//最小播放次数
                //轮播
                for (int b = 0 ; b < recordList.size();b++) {
                    if(minPlayNum == -1){
                        minPlayNum = recordList.get(b).getUseNum();
                        qaRecordFilePath = fileDir+Paths.get(recordList.get(b).getAnswerAudio()).getFileName().toString();
                    }else{
                        if (recordList.get(b).getUseNum() < minPlayNum) {
                            minPlayNum = recordList.get(b).getUseNum();
                            qaRecordFilePath = fileDir+Paths.get(recordList.get(b).getAnswerAudio()).getFileName().toString();
                        }
                    }
                }
            }

            int comid = 0;
            //是否开启评论记忆回复
            if(userModel.getKeywordKeeptype() == 1){
                comid = (int)comDb.insertData2(userName,userCom,type,2,qaRecordFilePath);
            }
            //第二步：判断当前是否正在素材回复
            if(materialKeywordPlayer != null) return;
            //第二步：判断当前是否正在问答回复
            if(qaKeywordPlayer != null) return;
            //没有正在问答回复和素材回复的，更新评论回复状态
            comDb.updateKeywordReply(comid,1);
            //开始播放
            QaKeywordPlay(qaRecordFilePath);
        }
    }
    //播放素材关键词回复（关闭话术和问答回复）【完结】
    private void MaterialKeywordPlay(String filePath) {
        //判断当前是否正在问答回复
        if(qaKeywordPlayer != null){
            qaKeywordPlayer.release();
            qaKeywordPlayer = null;
        }
        //判断是否开场白正在播放并且是可以打断
        if(prologuePlayer != null){
            //不允许打断
            if( userModel.getPrologueBreak() == 0) return;
            //允许打断 则判断打断的话术是否从开头播放 0不是（续播，记录播放的时间） 1是
            if(userModel.getPrologueRestart() == 0){
                //开场白允许打断，【暂停】播放
                prologuePlayer.pause();
                //获取当前播放位置
                prologuePlayCurrentPosition = prologuePlayer.getCurrentPosition();
            }else{
                //开场白不允许打断，【停止】播放
                prologuePlayer.release();
                prologuePlayer = null;
            }
        }
        //播放素材音频
        if(FileUtils.getFileExist(getApplicationContext(),filePath)){
            //问答找到了 文件路径不为空，且开始播放
            try {
                materialKeywordPlayer = new MediaPlayer();
                materialKeywordPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

                if(musicPlayer != null){
                    float volume = 0.2f; // 设置音量为20%，左右声道的音量都为20%
                    musicPlayer.setVolume(volume,volume);
                }
                materialKeywordPlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                materialKeywordPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        materialKeywordPlayer = null;
                        //播放完毕后  判断是否评论记忆回复
                        if(userModel.getKeywordKeeptype() == 1){
                            //查找素材回复类型
                            CommentModel commentModel = comDb.selectKeywordMateOld(3);
                            //判断是否开启了回复自动匹配素材关键词 开启则优先
                            if(materialKeywordStatus){
                                comDb.updateKeywordReply(commentModel.getCommentsId(),1);
                                MaterialKeywordPlay(commentModel.getKeywordAudio());
                                return;
                            }
                        }
                        //是否进行继续播放 话术是否暂停了
                        if(prologuePlayCurrentPosition != -1 && prologuePlayer != null){
                            prologuePlayer.seekTo(prologuePlayCurrentPosition);
                            prologuePlayer.start();
                            prologuePlayCurrentPosition = -1;
                        }else{
                            if(musicPlayer != null){
                                float volume = 1.0f; // 设置音量为100%(最大音量)，左右声道的音量都为50%
                                musicPlayer.setVolume(volume,volume);
                            }
                            //打断的话术是否重新播放 0不是（续播，记录播放的时间） 1是
                            if(userModel.getPrologueRestart() == 1 && prologuePlayer == null){
                                ProloguePlay();
                            }
                        }
                    }
                });
                materialKeywordPlayer.prepare();
                materialKeywordPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //播放问答关键词
    private void QaKeywordPlay(String filePath) {
        //判断是否开场白正在播放并且是可以打断
        if(prologuePlayer != null){
            //不允许打断
            if(userModel.getPrologueBreak() == 0) return;
            //允许打断 判断打断的话术是否从开头播放 0不是（续播，记录播放的时间） 1是
            if(userModel.getPrologueRestart() == 0){
                //开场白允许打断，【暂停】播放
                prologuePlayer.pause();
                //获取当前播放位置
                prologuePlayCurrentPosition = prologuePlayer.getCurrentPosition();
            }else{
                //开场白不允许打断，【停止】播放
                prologuePlayer.release();
                prologuePlayer = null;
            }
        }
        if(FileUtils.getFileExist(getApplicationContext(),filePath)){
            //问答找到了 文件路径不为空，且开始播放
            try {
                qaKeywordPlayer = new MediaPlayer();
                qaKeywordPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

                if(musicPlayer != null){
                    float volume = 0.2f; // 设置音量为20%，左右声道的音量都为20%
                    musicPlayer.setVolume(volume,volume);
                }
                qaKeywordPlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                qaKeywordPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        qaKeywordPlayer = null;
                        if(userModel.getKeywordKeeptype() == 1){
                            //查找素材回复类型
                            CommentModel commentModel = comDb.selectKeywordMateOld(2);
                            //判断是否开启了问答回复
                            if(qaKeywordStatus){
                                //存在未回复，开始回复
                                comDb.updateKeywordReply(commentModel.getCommentsId(),1);
                                QaKeywordPlay(commentModel.getKeywordAudio());
                                return;
                            }
                        }
                        //是否进行继续播放
                        if(prologuePlayCurrentPosition != -1 && prologuePlayer != null){
                            prologuePlayer.seekTo(prologuePlayCurrentPosition);
                            prologuePlayer.start();
                            prologuePlayCurrentPosition = -1;
                        }else{
                            if(musicPlayer != null){
                                float volume = 1.0f; // 设置音量为100%(最大音量)，左右声道的音量都为50%
                                musicPlayer.setVolume(volume,volume);
                            }
                            //打断的话术是否重新播放 0不是（续播，记录播放的时间） 1是
                            if(userModel.getPrologueRestart() == 1 && prologuePlayer == null){
                                ProloguePlay();
                            }
                        }
                    }
                });
                qaKeywordPlayer.prepare();
                qaKeywordPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //播放开场白
    private void ProloguePlay() {
        //关闭状态
        if(!prologuesStatus) return;

        String filePath = "";
        int minPlayNum = -1;
        int position = -1;
        if(userModel.getProloguePlaytype() == 1){
            //随机
            int randomNum = 0;
            if(proList.size() != 1){
                Random random = new Random();
                randomNum = random.nextInt(proList.size());
            }
            filePath = fileDir+Paths.get(proList.get(randomNum).getPrologueAudio()).getFileName().toString();
            position = randomNum;
        }else{
            //轮播
            for (int i = 0 ; i < proList.size();i++) {
                if(minPlayNum == -1){
                    minPlayNum = proList.get(i).getUseNum();
                    filePath = fileDir+Paths.get(proList.get(i).getPrologueAudio()).getFileName().toString();
                    position = i;
                }else{
                    if (proList.get(i).getUseNum() < minPlayNum) {
                        minPlayNum = proList.get(i).getUseNum();
                        filePath = fileDir+Paths.get(proList.get(i).getPrologueAudio()).getFileName().toString();
                        position = i;
                    }
                }
            }
        }
        //增加次数
        proList.get(position).setUseNum(proList.get(position).getUseNum()+1);
        if(FileUtils.getFileExist(getApplicationContext(),filePath)){
            try {
                Handler h1 = new Handler(Looper.getMainLooper());
                prologuePlayer = new MediaPlayer();
                prologuePlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                if(musicPlayer != null){
                    float volume = 0.2f; // 设置音量为20%，左右声道的音量都为20%
                    musicPlayer.setVolume(volume,volume);
                }
                prologuePlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                prologuePlayer.prepareAsync();
                prologuePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        // 媒体文件准备好后，设置延迟播放
                        h1.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if(prologuePlayer != null){
                                    prologuePlayer.start();
                                }
                            }
                        }, userModel.getPrologueInterval() * 1000); // 延迟10秒
                    }
                });
                prologuePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        prologuePlayer = null;
                        if(musicPlayer != null){
                            float volume = 1.0f; // 设置音量为100%(最大音量)，左右声道的音量都为50%
                            musicPlayer.setVolume(volume,volume);
                        }
                        ProloguePlay();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //播放背景音乐
    private void MusicPlay() {
        String filePath = "";
        int minPlayNum = -1;
        int position = -1;
        for (int i = 0 ; i < musicList.size();i++) {
            if(minPlayNum == -1){
                minPlayNum = musicList.get(i).getPlayNum();
                filePath = fileDir+Paths.get(musicList.get(i).getMusicUrl()).getFileName().toString();
                position = i;
            }else{
                if (musicList.get(i).getPlayNum() < minPlayNum) {
                    minPlayNum = musicList.get(i).getPlayNum();
                    filePath = fileDir+Paths.get(musicList.get(i).getMusicUrl()).getFileName().toString();
                    position = i;
                }
            }
        }
        musicList.get(position).setPlayNum(musicList.get(position).getPlayNum()+1);
        if(FileUtils.getFileExist(getApplicationContext(),filePath)){
            musicPlayer = new MediaPlayer();
            musicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                musicPlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                musicPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        mediaPlayer = null;
                        MusicPlay();
                    }
                });
                musicPlayer.prepare();
                musicPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //=======================勿动区域=================================
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(WsMessageEvent wsMessageEvent){
        switch (wsMessageEvent.getNumber()) {
            case WsStatus.onOpen://onOpen
                isConnected = true;
                //发送开始校验
                SendMessage(WsStatus.mateialCheck,true);
                break;
            case WsStatus.onMessageString://onMessage
                MessageReceive(wsMessageEvent.getMessage());
                break;
            case WsStatus.onMessageByteBuffer://onMessage
                try {
                    fos.write(wsMessageEvent.getBuffer().array());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case WsStatus.onClose://onClose
                isConnected = false;
                break;
            case WsStatus.onError://onError
                break;
        }
    }
    //文件同步机制
    private void setDataToList(String json){
        try {
            keyList = new ArrayList<>();
            proList = new ArrayList<>();
            musicList = new ArrayList<>();
            groupList = new ArrayList<>();
            fileNoExistsList = new ArrayList<>();

            JSONObject allJson = new JSONObject(json);

            userModel = UserModel.json2Model(allJson.getJSONObject("user"));

            JSONArray keyArray = allJson.getJSONArray("keyword_array");
            for (int i = 0 ; i < keyArray.length();i++) {
                keyList.add(KeywordModel.Json2model(keyArray.getJSONObject(i)));
            }

            JSONArray proArray = allJson.getJSONArray("prologue_array");
            for (int i = 0 ; i < proArray.length();i++) {
                proList.add(PrologueModel.Json2model(proArray.getJSONObject(i)));
            }

            JSONArray musicArray = allJson.getJSONArray("music_array");
            for (int i = 0 ; i < musicArray.length();i++) {
                musicList.add(MusicModel.Json2model(musicArray.getJSONObject(i)));
            }

            JSONArray groupArray = allJson.getJSONArray("group_array");
            for (int i = 0 ; i < groupArray.length();i++) {
                groupList.add(ProductGroupModel.Json2model(groupArray.getJSONObject(i)));
            }
            //【关键词】查询回复音频是否存在
            for (KeywordModel m:keyList) {
                for (KeywordRecordModel rm: m.getListRecord()) {
                    String audio_file_path = fileDir+Paths.get(rm.getAnswerAudio()).getFileName().toString();
                    if(!new File(audio_file_path).exists()){
                        boolean isHas = false;
                        for (String s:fileNoExistsList) {
                            if(s.equals(rm.getAnswerAudio())){
                                isHas = true;
                                break;
                            }
                        }
                        if(!isHas) fileNoExistsList.add(rm.getAnswerAudio());
                    }
                }
            }
            //【音乐】查询回复音频是否存在
            for (MusicModel m:musicList) {
                String audio_file_path = fileDir+Paths.get(m.getMusicUrl()).getFileName().toString();
                if(!new File(audio_file_path).exists()){
                    boolean isHas = false;
                    for (String s:fileNoExistsList) {
                        if(s.equals(m.getMusicUrl())){
                            isHas = true;
                            break;
                        }
                    }
                    if(!isHas) fileNoExistsList.add(m.getMusicUrl());
                }
            }
            //【话术】查询回复音频是否存在
            for (PrologueModel m:proList) {
                String audio_file_path = fileDir+Paths.get(m.getPrologueAudio()).getFileName().toString();
                if(!new File(audio_file_path).exists()){
                    boolean isHas = false;
                    for (String s:fileNoExistsList) {
                        if(s.equals(m.getPrologueAudio())){
                            isHas = true;
                            break;
                        }
                    }
                    if(!isHas) fileNoExistsList.add(m.getPrologueAudio());
                }
            }
            //【产品组】查询素材和回复音频是否存在
            for (ProductGroupModel m:groupList) {
                for (ProductMaterialRecordModel rm: m.getListRecord()) {
                    //素材文件
                    String material_file_path = fileDir+Paths.get(rm.getMaterialFilepath()).getFileName().toString();
                    if(!new File(material_file_path).exists()){
                        boolean isHas = false;
                        for (String s:fileNoExistsList) {
                            if(s.equals(rm.getMaterialFilepath())){
                                isHas = true;
                                break;
                            }
                        }
                        if(!isHas) fileNoExistsList.add(rm.getMaterialFilepath());
                    }
                    //设置了回复音频
                    if(rm.getAnswerState() != 0){
                        String audio_file_path = fileDir+Paths.get(rm.getAnswerAudio()).getFileName().toString();
                        if(!new File(audio_file_path).exists()){
                            boolean isHas = false;
                            for (String s:fileNoExistsList) {
                                if(s.equals(rm.getAnswerAudio())){
                                    isHas = true;
                                    break;
                                }
                            }
                            if(!isHas) fileNoExistsList.add(rm.getAnswerAudio());
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //发送文件完毕
    private void transFileOver(String param){
        try {
            //关闭输出流
            if (fos != null) {
                fos.close();
            }
            //查询当前是否记录该原路径
            for (int i = 0 ; i < fileNoExistsList.size();i++){
                if(fileNoExistsList.get(i).equals(param)){
                    fileNoExistsList.remove(i);
                    break;
                }
            }
            if(fileNoExistsList.size() > 0){
                String old_file_path = fileNoExistsList.get(fileNoExistsList.size()-1);
                //实例化输出流
                fos = new FileOutputStream(fileDir+Paths.get(old_file_path).getFileName().toString());
                //请求发送文件
                SendMessage(WsStatus.transFile,old_file_path);
            }else{
                //暂无可同步的文件
                SendMessage(WsStatus.mateialSync,0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //消息发送模版
    private void SendMessage(String magType, Object obj){
        try {
            JSONObject json = new JSONObject();
            json.put("command",magType);
            json.put("param",obj);
            WsClient.Send(json.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //弹窗链接
    private void dialog_connected(){
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_ws_connect);
        final EditText dialog_ws_connect_ip = window.findViewById(R.id.dialog_ws_connect_ip);
        final EditText dialog_ws_connect_port = window.findViewById(R.id.dialog_ws_connect_port);
        final TextView dialog_ws_connect_no = window.findViewById(R.id.dialog_ws_connect_no);
        final TextView dialog_ws_connect_ok = window.findViewById(R.id.dialog_ws_connect_ok);

        //取出当前值
        IpconfigModel model = db.select();
        if(model.getServerIp() != null){
            dialog_ws_connect_ip.setText(model.getServerIp());
            dialog_ws_connect_port.setText(model.getServerPort());
        }
        dialog_ws_connect_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
        dialog_ws_connect_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String ip = dialog_ws_connect_ip.getText().toString();
                String port = dialog_ws_connect_port.getText().toString();
                //更新
                db.updateServer(ip,port);
                // 发起连接
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        WsClient.connect(getApplicationContext(),ip+":"+port);
                    }
                }).start();
                dialog.dismiss();
            }
        });
    }
    //根据路径获取音频的时长
    public long getAudioDuration(String filePath) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        long duration = 0;
        try {
            retriever.setDataSource(filePath);
            String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            duration = Long.parseLong(durationStr);
            retriever.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return duration;
    }

    @Override
    protected void onResume() {
        //在Activity已可见，获取焦点开始与用户交互时调用；
        super.onResume();
        // 获取锁
        wakeLock.acquire();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        EventBus.getDefault().unregister(this);
        //取消链接
        WsClient.Close();

        if(musicPlayer != null){
            musicPlayer.release();
        }
        if(prologuePlayer != null){
            prologuePlayer.release();
        }
        if(qaKeywordPlayer != null){
            qaKeywordPlayer.release();
        }
        if(materialKeywordPlayer != null){
            materialKeywordPlayer.release();
        }
        //释放锁
        if (wakeLock != null) {
            wakeLock.release();
        }
    }
    //获取锁
    private void acquireWakeLock() {
        if(wakeLock == null) {
            // 获取电源管理器
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            // 设置 WakeLock
            wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyApp:WakeLockTag");
            // 保持屏幕常亮
            getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }
    /* 添加函数onWindowFocusChanged */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}